package products

import (
	images2 "cloud_android_backend/pkg/models/images"
	"cloud_android_backend/pkg/models/products"
	"cloud_android_backend/pkg/models/resources"
	"github.com/golang/glog"
	"modules.tenxcloud.com/common/composite"
)

type ProductsListWithInfo struct {
	ProductsList    []ProductsWithInstanceCount
	AndroidVersions []int
}
type ProductsWithInstanceCount struct {
	products.Products
	InstanceCount int `json:"instance_count""`
}

func GetProductsLists() (ProductsListWithInfo, error) {
	var productsList ProductsListWithInfo
	db, err := composite.Database.GetOrm()
	if err != nil {
		return productsList, err
	}
	images := &images2.Images{}
	imagesList, err := images.GetAll(db)
	if err != nil {
		return productsList, err
	}
	androidVersions := make([]int, 0)
	for _, image := range imagesList {
		androidVersions = append(androidVersions, image.AndroidVersion)
	}
	ProductModel := &products.Products{}
	ProductListWithPackages, err := ProductModel.GetAllWithPackages(db)
	if err != nil {
		return productsList, err
	}
	var ProductListWithInstanceCount []ProductsWithInstanceCount
	for _, product := range ProductListWithPackages {
		instanceModel := &resources.Instances{ProductId: product.Id, CatId: product.CatId}
		count, _ := instanceModel.CountUnusedByCatId(db)
		productWithInstanceCount := ProductsWithInstanceCount{
			Products:      product,
			InstanceCount: count,
		}
		ProductListWithInstanceCount = append(ProductListWithInstanceCount, productWithInstanceCount)
	}
	productsList = ProductsListWithInfo{
		ProductsList:    ProductListWithInstanceCount,
		AndroidVersions: androidVersions,
	}
	return productsList, nil
}

func GetProductPackagesList(productId int) (ProductsWithInstanceCount, error) {
	var productPackages ProductsWithInstanceCount
	ProductModel := &products.Products{Id: productId}
	db, err := composite.Database.GetOrm()
	if err != nil {
		glog.Error(err)
		return productPackages, err
	}

	err = ProductModel.GetByIdWithPackages(db)
	if err != nil {
		//if gorm.IsRecordNotFoundError(err) {
		//	return productPackages, nil
		//}
		glog.Error(err)
		return productPackages, err
	}
	instanceModel := &resources.Instances{ProductId: productId, CatId: ProductModel.CatId}
	count, _ := instanceModel.CountUnusedByCatId(db)
	productPackages = ProductsWithInstanceCount{
		Products:      *ProductModel,
		InstanceCount: count,
	}
	return productPackages, nil
}
